package multiplayer;

import Entities.*;
import Visitor.BallCollisionVisitor;
import Visitor.IVisitor;
import Visitor.MoveVisitor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PhaseControllerCliente1 extends Thread implements PhaseController, KeyListener {

    private Bar bar1;
    private Bar bar2;
    private Scene scene;
    private ArrayList<Ball> ballList;

    public PhaseControllerCliente1() {
        scene = new Scene();
        scene.addChild(new Boundary(0, 0, 399, 299));
        scene.addChild(new Ball(50, 50, 1, 1, 2));

        bar1 = new Bar(0, 250);
        bar2 = new Bar(0, 20);

        scene.addChild(bar1);
        scene.addChild(bar2);

        ballList = new ArrayList<>();
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(5);

                for (int i = 0; i < scene.getNumElems(); i++) {
                    if (scene.getChild(i) instanceof Ball) {
                        ballList.add((Ball) scene.getChild(i));
                    }
                }
                for (Ball b : ballList) {
                    IVisitor ballCollisionVisitor = new BallCollisionVisitor(b);
                    scene.accept(ballCollisionVisitor);
                }
                IVisitor visitor = new MoveVisitor(false, false, false, 400);
                scene.accept(visitor);
            } catch (InterruptedException ex) {
                Logger.getLogger(PhaseControllerCliente1.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Bar1: " + bar1.getX() + " Bar2: " + bar2.getX());
        }
    }

    public void setXBar2(int x) {
        bar2.setX(x);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            if (bar1.getX() >= 3) {
                bar1.setX(bar1.getX() - 3);
            } else {
                bar1.setX(0);
            }
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            if (bar1.getX() <= 396) {
                bar1.setX(bar1.getX() + 3);
            } else {
                bar1.setX(399);
            }
        }
        System.out.println(bar1.getX());
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void execute() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Scene getScene() {
        return scene;
    }
}
